package com.qsl.excel;

import com.linuxense.javadbf.DBFDataType;
import com.linuxense.javadbf.DBFField;
import com.linuxense.javadbf.DBFWriter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description:
 * @Author: 博客园@青石路
 * @CreateDate: 2023/2/7 14:56
 **/
public class FieldTypeTest {

    private static final String XLS = "xls";
    private static final String XLSX = "xlsx";

    public static void main(String[] args) {
        // 设定Excel文件所在路径
        //String excelFileName = "D:\\中行关联方股票调出_20221215.xlsx";
        String excelFileName = "D:\\中债债券预期信用损失2023020117590754533.xlsx";
        // 读取Excel文件内容
        readExcel(excelFileName);
    }

    public static void readExcel(String fileName) {

        Workbook workbook = null;
        FileInputStream inputStream = null;

        try {
            // 获取Excel后缀名
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            // 获取Excel文件
            File excelFile = new File(fileName);
            if (!excelFile.exists()) {
                System.out.println("文件不存在");
            }

            // 获取Excel工作簿
            inputStream = new FileInputStream(excelFile);
            workbook = getWorkbook(inputStream, fileType);

            // 读取excel中的数据
            parseExcel(workbook);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != workbook) {
                    workbook.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据文件后缀名类型获取对应的工作簿对象
     * @param inputStream 读取文件的输入流
     * @param fileType 文件后缀名类型（xls或xlsx）
     * @return 包含文件数据的工作簿对象
     * @throws IOException
     */
    public static Workbook getWorkbook(InputStream inputStream, String fileType) throws IOException {
        Workbook workbook = null;
        if (fileType.equalsIgnoreCase(XLS)) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (fileType.equalsIgnoreCase(XLSX)) {
            workbook = new XSSFWorkbook(inputStream);
        }
        return workbook;
    }

    /**
     * 解析Excel数据
     * @param workbook Excel工作簿对象
     * @return 解析结果
     */
    private static void parseExcel(Workbook workbook) throws FileNotFoundException {

        DBFWriter writer = new DBFWriter(new FileOutputStream(new File("abc.dbf")));

        // 解析sheet
        for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
            Sheet sheet = workbook.getSheetAt(sheetNum);

            // 校验sheet是否合法
            if (sheet == null) {
                continue;
            }

            // 获取第一行数据
            int firstRowNum = sheet.getFirstRowNum();
            Row firstRow = sheet.getRow(firstRowNum);
            if (null == firstRow) {
                System.out.println("解析Excel失败，在第一行没有读取到任何数据！");
            }

            // 解析每一行的数据，构造数据对象
            int rowStart = firstRowNum;
            int rowEnd = sheet.getPhysicalNumberOfRows();
            // 定义DBF文件字段
            setDbfField(sheet.getRow(0), writer);
            for (int rowNum = 1; rowNum < 3; rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (null == row) {
                    continue;
                }
                convertRowToDbf(row);
            }
        }
    }

    private static void setDbfField(Row row, DBFWriter writer) {
        DBFField[] fields = new DBFField[row.getLastCellNum()];
        short firstCellNum = row.getFirstCellNum();
        short lastCellNum = row.getLastCellNum();
        for (int i=firstCellNum; i<lastCellNum; i++) {
            Cell cell = row.getCell(i);
            fields[i] = new DBFField();
            fields[i].setName(cell.getStringCellValue());
            CellType cellTypeEnum = cell.getCellTypeEnum();
            switch (cellTypeEnum) {
                case NUMERIC:
                    fields[i].setType(DBFDataType.NUMERIC);
                    fields[i].setLength(23);
                    break;
                default:
                    // 默认当字符串处理
                    fields[i].setType(DBFDataType.CHARACTER);
                    fields[i].setLength(254);
                    break;
            }
        }
        writer.addRecord(fields);
        writer.close();
    }

    /**
     * 提取每一行中需要的数据，构造成为一个结果数据对象
     *
     * 当该行中有单元格的数据为空或不合法时，忽略该行的数据
     *
     * @param row 行数据
     * @return 解析后的行数据对象，行数据错误时返回null
     */
    private static void convertRowToDbf(Row row) {
        short firstCellNum = row.getFirstCellNum();
        short lastCellNum = row.getLastCellNum();
        System.out.println("firstCellNum = " + firstCellNum);
        System.out.println("lastCellNum = " + lastCellNum);
        for (int i=firstCellNum; i<lastCellNum; i++) {
            Cell cell = row.getCell(i);
            System.out.print(cell.getCellType() + " ");
        }
    }
}
